import random

from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from django.contrib import messages
from myApp.models import *
from utils.querys import *
from utils.getPublicData import *
from utils.getChartData import *
from machine.index import *
from recommend.machie import *
# Create your views here.

def index(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    typeChartData,topX,topY1,topY2,boxLineX,boxLineY1,boxLineY2,countryX,countryY,starData,boxTopMovieList = getIndexData()
    maxType = max([x[2] for x in boxTopMovieList])
    maxBox = boxTopMovieList[0][11]
    maxBoxMovie = boxTopMovieList[0][0]
    return render(request,'index.html',{
        'userInfo':userInfo,
        'typeChartData':typeChartData,
        'topX':topX,
        'topY1':topY1,
        'topY2':topY2,
        'boxLineX': boxLineX,
        'boxLineY1': boxLineY1,
        'boxLineY2': boxLineY2,
        'countryX': countryX,
        'countryY': countryY,
        'starData': starData,
        'boxTopMovieList':boxTopMovieList,
        'maxType':maxType,
        'maxBox':maxBox,
        'maxBoxMovie':maxBoxMovie
    })

def chartOne(request):

    # 尝试从 session 获取用户名
    uname = request.session.get('username')

    if not uname:
        # 如果 session 中没有用户名，则尝试从 GET 请求中获取
        uname = request.GET.get('uname')

    if not uname:
        # 如果无法获取到用户名，重定向到登录页
        return redirect('login')  # 假设你有一个名为 'login' 的登录页面

    # 根据获取的用户名查询用户信息
    userInfo = User.objects.get(username=uname)

    typeList,typeAvgData = getTypeChartData()
    defaultType = request.GET.get('typeName') or '科幻'
    print(defaultType)
    boxDataX,boxDataY,rateDataX,rateDataY = getChartOneByType(defaultType)
    return render(request,'chartOne.html',{
        'userInfo':userInfo,
        'typeList':typeList,
        'defaultType':defaultType,
        'boxDataX': boxDataX,
        'boxDataY': boxDataY,
        'rateDataX': rateDataX,
        'rateDataY': rateDataY,
        'typeAvgData':typeAvgData
    })


def rateChart(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    mYearX,mYearY,mCountryX,mCountryY,mTypeX,mTypeY = getRateChartData()
    return render(request,'rateChart.html',{
        'userInfo':userInfo,
        'mYearX':mYearX,
        'mYearY':mYearY,
        'mCountryX':mCountryX,
        'mCountryY':mCountryY,
        'mTypeX':mTypeX,
        'mTypeY':mTypeY
    })

def timeChart(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    mYearX,mYearY,mMonthX,mMonthY,durationData = getTimeChartData()
    return render(request,'timeChart.html',{
        'userInfo':userInfo,
        'mYearX': mYearX,
        'mYearY': mYearY,
        'mMonthX': mMonthX,
        'mMonthY': mMonthY,
        'durationData': durationData,
    })


def boxChart(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    mTypeBoxX,mTypeBoxY,mCountryBoxX,mCountryBoxY,mYearX,mYearY = getBoxChartData()
    return render(request,'boxChart.html',{
        'userInfo':userInfo,
        'mTypeBoxX': mTypeBoxX,
        'mTypeBoxY': mTypeBoxY,
        'mCountryBoxX': mCountryBoxX,
        'mCountryBoxY': mCountryBoxY,
        'mYearX': mYearX,
        'mYearY':mYearY
    })


def tableData(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    movieData = list(getcatMovieData())
    return render(request,'tableData.html',{
        'userInfo':userInfo,
        'movieData':movieData[:30]
    })


def changeInfo(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    if request.method == 'POST':
        print(request.POST)
        res = changePwd(userInfo,request.POST)
        if res != None:
            messages.error(request,res)
            return HttpResponseRedirect('/myApp/changeInfo/')
        userInfo = User.objects.get(username=uname)
        messages.success(request,'修改成功')
    return render(request,'changeInfo.html',{
        'userInfo':userInfo,
    })


def collectData(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    movieList = getUserHistory(userInfo)

    return render(request,'collectData.html',{
        'userInfo':userInfo,
        'movieList':movieList
    })


def movieCloud(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)


    return render(request,'movieCloud.html',{
        'userInfo':userInfo,
    })


def actorCloud(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)


    return render(request,'actorCloud.html',{
        'userInfo':userInfo,
    })

def recommendation(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    recommendData = []
    try:
        user_ratings = getUser_ratings()
        recommended_items = user_col_filter(uname,user_ratings)
        for item in recommended_items:
            data_list = queryhive('select * from catMovieData where id = %d',[item],'select')[0]
            data_list = list(data_list)
            recommendData.append(data_list)
    except:
        recommendData = queryhive('select * from catMovieData',[],'select')

    if len(recommendData) == 0:
        recommendData = queryhive('select * from catMovieData',[],'select')
    if len(recommendData) >= 4:
        recommendData = random.sample(recommendData,4)
    return render(request,'recommendation.html',{
        'userInfo':userInfo,
        'recommendData':recommendData
    })



def predict(request):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    movieList = list(getcatMovieData())
    typeList,typeAvgData = getTypeChartData()
    countryList = [x[3] for x in movieList]
    print(typeList,countryList)
    if request.method == 'POST':
        defaultType = request.POST.get('type')
        defaultCountry = request.POST.get('country')
        defaultFirstBox = request.POST.get('firstBox')
        print(defaultType,defaultCountry,defaultFirstBox)
        boxResult = predict_boxOffice(defaultType,defaultCountry,defaultFirstBox)
        print(boxResult)
        return render(request, 'predict.html', {
            'userInfo': userInfo,
            'typeList': typeList,
            'countryList': countryList,
            'boxResult':boxResult
        })
    return render(request,'predict.html',{
        'userInfo':userInfo,
        'typeList':typeList,
        'countryList':countryList
    })

def addHistory(request,movieId):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    a = uname
    addHistoryData(userInfo,movieId)
    return HttpResponseRedirect('/myApp/collectData/')


def delHisotry(request,movieId):
    uname = request.session.get('username')
    userInfo = User.objects.get(username=uname)
    a = uname
    addHistoryData(userInfo,movieId)
    data = History.objects.filter(user=userInfo,movieId=movieId)
    data.delete()
    return HttpResponseRedirect('/myApp/collectData/')

def logOut(request):
    request.session.clear()
    return redirect('login')

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html', {})
    else:
        logusername = request.POST.get('logusername')
        logpassword = request.POST.get('logpassword')
        print(logusername,logpassword)
        try:
            user = User.objects.get(username=logusername,password=logpassword)
            if user.user_type==1:
                request.session['username'] = logusername
                return redirect('/myApp/list_tables/')
            else:
                request.session['username'] = logusername
                return redirect('/myApp/index/')
        except:
            messages.error(request,'请输入正确的用户名或密码')
            return HttpResponseRedirect('/myApp/login/')

def register(request):
    if request.method == 'GET':
        return render(request,'register.html',{})
    else:
        uname = request.POST.get('username')
        password = request.POST.get('password')
        ckPassword = request.POST.get('ckPassword')
        print(uname,password,ckPassword)
        try:
            User.objects.get(username=uname)
            message = '用户名已被注册'
            messages.error(request,message)
            return HttpResponseRedirect('/myApp/register/')
        except:
            if not uname or not password or not ckPassword:
                message = '注册信息不可为空，请您输入完整'
                messages.error(request, message)
                return HttpResponseRedirect('/myApp/register/')
            elif password != ckPassword:
                message = '确认密码失败，请您重新输入'
                messages.error(request, message)
                return HttpResponseRedirect('/myApp/register/')
            else:
                User.objects.create(username=uname,password=password)
                messages.success(request, '恭喜您!注册成功')
                return HttpResponseRedirect('/myApp/login/')





